# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-07-04
# @File : 4_register_complete.py

import requests
import uuid
import base64
import ddddocr


def fetch_image_code(mobile, app_key, device_identify):
    res = requests.get(
        url="https://newappuser.jiuxian.com/messages/graphCode.htm",
        params={
            "appKey": app_key,
            "appVersion": "9.0.30",
            "areaId": "500",
            "channelCode": "0",
            "cpsId": "xiaomi",
            "deviceIdentify": device_identify,
            "deviceType": "ANDROID",
            "deviceTypeExtra": "0",
            "equipmentType": "Pixel 2 XL",
            "mobile": mobile,
            "netEnv": "wifi",
            "pushToken": "Akuwre13Fge-QlvEvjef4neaohHC8S48koHzVyRtdH8x",
            "screenReslolution": "1440x2712",
            "supportWebp": "1",
            "sysVersion": "10",
            "type": "4"
        },
        headers={
            "secure": "false",
            "Accept-Encoding": "gzip",
            'user-agent': "okhttp/3.14.9",
            'Host': "newappuser.jiuxian.com",
            'Connection': "keep-alive"
        },
    )
    print(res.json())
    image_str = res.json()['result']["imgCode"]

    image_bytes = base64.b64decode(image_str)

    with open("v2.png", mode='wb') as f:
        f.write(image_bytes)

    image_str = res.json()['result']["imgCode"]

    img = base64.b64decode(image_str)

    ocr = ddddocr.DdddOcr(show_ad=False)
    code = ocr.classification(img)
    return code


def check_image_code(mobile, code, app_key, device_identify):
    res = requests.get(
        url='https://newappuser.jiuxian.com/messages/mobileCode.htm',
        params={
            "appKey": app_key,
            "appVersion": "9.0.30",
            "areaId": "500",
            "channelCode": "0",
            "code": code,
            "cpsId": "xiaomi",
            "deviceIdentify": device_identify,
            "deviceType": "ANDROID",
            "deviceTypeExtra": "0",
            "equipmentType": "Pixel 2 XL",
            "mobile": mobile,
            "netEnv": "wifi",
            "screenReslolution": "1440x2712",
            "supportWebp": "1",
            "sysVersion": "10",
            "type": "1"
        }
    )
    data_dict = res.json()

    # {'result': '', 'errCode': '', 'success': '1', 'errMsg': ''}
    # {'result': '', 'errCode': '1200013', 'success': '0', 'errMsg': '验证码输入错误'}
    # print(data_dict)
    return data_dict.get('success') == "1"


def login_by_sms(mobile, sms_code, app_key, device_identify):
    res = requests.post(
        url="https://newappuser.jiuxian.com/user/loginMobileFast.htm",
        data={
            "appKey": app_key,
            "appVersion": "9.0.30",
            "areaId": "500",
            "channelCode": "0",
            "cpsId": "xiaomi",
            "deviceIdentify": device_identify,
            "deviceType": "ANDROID",
            "deviceTypeExtra": "0",
            "equipmentType": "Pixel 2 XL",
            "mobile": mobile,
            "netEnv": "wifi",
            # "pushToken": "AhS6iYcX9O27VIbFSb0u_833znG4CsMcluENUODhFSUy",
            "screenReslolution": "1440x2712",
            "supportWebp": "1",
            "sysVersion": "10",
            "verifyCode": sms_code
        }
    )
    # {"result":"","errCode":"1200003","success":"0","errMsg":"验证码错误或已过期，请重新输入"}
    # {"result":{...},"errCode":"1200093","success":"1","errMsg":"初始化密码"}
    # {"result":{...},"errCode":"","success":"1","errMsg":""}
    data_dict = res.json()
    return data_dict.get("success") == "1", data_dict.get('result')


def run():
    mobile = input("请输入你的手机号码:\n")
    app_key = device_identify = str(uuid.uuid4())
    while True:
        img_code = fetch_image_code(mobile, app_key, device_identify)
        status = check_image_code(mobile, img_code, app_key, device_identify)
        if status:
            break

    sms_code = input("请输入验证码：")

    status, data_dict = login_by_sms(mobile, sms_code, app_key, device_identify)
    if not status:
        print("登录失败")
        return
    print("登录成功")
    print(data_dict)


if __name__ == '__main__':
    run()
